package com.sentrix.auto.printercenter.infrastructure.agentserver;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Slf4j
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 如果是HTTP请求，获取session并存储到属性中
        if (request instanceof ServletServerHttpRequest servletRequest) {
            HttpSession session = servletRequest.getServletRequest().getSession();
            if (session != null) {
                // 可以从session或请求参数中获取用户信息等
                String clientId = servletRequest.getServletRequest().getParameter("clientId");
                if (clientId != null && !clientId.isEmpty()) {
                    attributes.put("clientId", clientId);
                    log.info("客户端连接: " + clientId);
                    return true;
                } else {
                    log.info("客户端连接失败: 缺少clientId参数");
                    return true;
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("握手完成");
    }
}
